/*
 * @(#)DependencyModel.java $version 2013. 11. 26.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.i2.june.dependency.model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author kimseongjune@nhn.com
 */
public class DependencyModel {
	private String id;
	private Map<String, DependencyModel> dependencyMap;
	private int dependencyCount;
	
	private DependencyModel() {
		
	}
	
	public static DependencyModel create(String id) {
		DependencyModel instance = new DependencyModel();
		
		instance.id = id;
		instance.dependencyMap = new HashMap<String, DependencyModel>();
		instance.dependencyCount = 0;
		
		return instance;
	}

	public String getId() {
		return this.id;
	}

	public void addDependency(DependencyModel importedModel) {
		dependencyMap.put(importedModel.getId(), importedModel);
		importedModel.addDependencyCount();
	}

	private void addDependencyCount() {
		this.dependencyCount++;
	}

	public Map<String, DependencyModel> getDependencyMap() {
		return dependencyMap;
	}

	public int getDependencyCount() {
		return dependencyCount;
	}

	public Map<String, DependencyModel> simulateRemove() {
		Map<String, DependencyModel> updatedDependencyMap = new HashMap<String, DependencyModel>();
		
		recursiveSimulateRemove(updatedDependencyMap);
		
		return updatedDependencyMap;
	}

	private void recursiveSimulateRemove(Map<String, DependencyModel> resultMap) {
		Set<String> keySet = dependencyMap.keySet();
		Iterator<String> keyIterator = keySet.iterator();
		
		while (keyIterator.hasNext()) {
			String key = keyIterator.next();
			DependencyModel original = dependencyMap.get(key);
			original.recursiveSimulateRemove(resultMap);
			
			if (resultMap.containsKey(key)) {
				DependencyModel updated = resultMap.get(key);
				updated.dependencyCount = updated.dependencyCount - 1;
			} else {
				DependencyModel updated = DependencyModel.create(original.getId());
				updated.dependencyCount = original.dependencyCount - 1;
				resultMap.put(updated.id, updated);
			}
		}
	}
}
